package api

import (
	"errors"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/smash-llj/Nexa-server/models/request"
	service "github.com/smash-llj/Nexa-server/service"
	utils "github.com/smash-llj/Nexa-server/utils"
)

type SessionApi struct {
	BaseApi
	Service *service.SessionService
}

func NewSessionApi() *SessionApi {
	return &SessionApi{
		BaseApi: NewBaseApi(),
		Service: service.NewSessionService(),
	}
}

// CreateSession 创建会话
func (s SessionApi) CreateSession(C *gin.Context) {
	var friendDto request.UserFriendReq
	if err := C.ShouldBind(&friendDto); err != nil {
		s.Fail(Response{Msg: err.Error()})
		return
	}
	sessionId, err := s.Service.CreateSession(friendDto)
	if err != nil {
		s.Fail(Response{Msg: err.Error()})
		return
	}
	C.JSON(http.StatusOK, gin.H{
		"data": sessionId,
	})
}

// RecentChatSession 获取最近会话列表
func (s SessionApi) RecentChatSession(C *gin.Context) {
	UserID := utils.GetUserId(C)
	list, err := s.Service.RecentChatSession(UserID)
	if err != nil {
		s.Fail(Response{Msg: err.Error()})
		return
	}
	C.JSON(http.StatusOK, gin.H{
		"data": list,
	})
}

// UpdateSessionUnread 更新未读消息
func (s SessionApi) UpdateSessionUnread(C *gin.Context) {
	s.BaseApi.C = C
	userId := utils.GetUserId(C)

	if err := s.Service.UpdateSessionUnread(userId); err != nil {
		s.Fail(Response{Msg: err.Error()})
		return
	}
	s.Success(Response{Data: "ok"})
}

// PinnedSession 置顶会话
func (s SessionApi) PinnedSession(C *gin.Context) {
	uid := utils.GetUserId(C)
	sessionId := C.Param("sessionId")
	if sessionId == "" {
		s.Fail(Response{Msg: errors.New("sessionId不能为空")})
		return
	}
	ok, err := s.Service.PinnedSession(uid, sessionId)
	if err != nil {
		s.Fail(Response{Msg: err.Error()})
		return
	}
	C.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": ok,
	})
}
